import { createApp } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { createPinia } from 'pinia'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/reset.css'

import App from './App.vue'
import { routes } from './router/index.js'
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper'

let app = null
let router = null
let pinia = null

function render(props = {}) {
  const { container } = props
  
  // 创建路由实例
  router = createRouter({
    history: createWebHistory(qiankunWindow.__POWERED_BY_QIANKUN__ ? '/vue3' : '/'),
    routes
  })
  
  // 创建Pinia状态管理
  pinia = createPinia()
  
  // 创建Vue应用实例
  app = createApp(App)
  app.use(router)
  app.use(pinia)
  app.use(Antd)
  
  // 挂载到容器
  const containerEl = container ? container.querySelector('#app') : '#app'
  app.mount(containerEl)
  
  console.log('Vue3 微应用已挂载', { container, props })
}

// 乾坤生命周期配置
renderWithQiankun({
  // 微应用挂载
  mount(props) {
    console.log('🚀 Vue3微应用开始挂载', props)
    render(props)
  },
  
  // 微应用启动
  bootstrap() {
    console.log('📦 Vue3微应用启动完成')
  },
  
  // 微应用卸载
  unmount() {
    console.log('🔌 Vue3微应用开始卸载')
    if (app) {
      app.unmount()
      app = null
      router = null
      pinia = null
    }
  },
  
  // 更新props
  update(props) {
    console.log('🔄 Vue3微应用更新props', props)
  }
})

// 独立运行时的启动逻辑
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  console.log('🎯 Vue3应用独立运行模式')
  render()
}